package files;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtility {

	/**
	 * Zips file contained in <i>filename</i> to a zip file in
	 * <i>zipFileName</i>.
	 * 
	 * The file is zipped with no regards to it's directory structure.
	 * 
	 * @param filename
	 *            file to be zipped
	 * @param zipFilename
	 *            destination file after zipping
	 */
	public static void doZip(String filename, String zipFilename) {

		int last = filename.lastIndexOf(System.getProperty("file.separator"));

		String fileTitle = filename.substring(last + 1);
		String filePath = filename.substring(0, last + 1);

		doZip(filePath, fileTitle, zipFilename);

	}

	private static void doZip(String folder, String filename, String zipfilename) {
		try {
			byte[] buf = new byte[1024];
			FileInputStream fis = new FileInputStream(folder + filename);
			fis.read(buf, 0, buf.length);

			CRC32 crc = new CRC32();
			ZipOutputStream s = new ZipOutputStream((OutputStream) new FileOutputStream(zipfilename));

			s.setLevel(6);

			ZipEntry entry = new ZipEntry(filename);
			entry.setSize((long) buf.length);
			crc.reset();
			crc.update(buf);
			entry.setCrc(crc.getValue());
			s.putNextEntry(entry);
			s.write(buf, 0, buf.length);
			s.finish();
			s.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void doZip(List<String> filenames, String zipFilename) {
		// String filePath = absoluteFilename.substring(0, last + 1);

		try {
			CRC32 crc = new CRC32();
			ZipOutputStream s = new ZipOutputStream((OutputStream) new FileOutputStream(zipFilename));

			s.setLevel(6);
			for (String absoluteFilename : filenames) {

				int last = absoluteFilename.lastIndexOf(System.getProperty("file.separator"));

				String filename = absoluteFilename.substring(last + 1);

				byte[] buf = new byte[1024];
				FileInputStream fis = new FileInputStream(absoluteFilename);

				ZipEntry entry = new ZipEntry(filename);

				// entry.setSize((long) buf.length);
				crc.reset();
				crc.update(buf);
				entry.setCrc(crc.getValue());
				s.putNextEntry(entry);
				int count=0;
				while ((count = fis.read(buf, 0, buf.length))!=-1) {
					s.write(buf, 0, count);
				}
				fis.close();
			}
			s.finish();
			s.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
